package com.ylx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/menu.jsp")
public class JingliFilter implements Filter {
    public void destroy () {
    }

    public void doFilter (ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        chain.doFilter(req, resp);
        HttpServletRequest request =(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        //获得用户提交的uri
        String uri = request.getRequestURI();
        if (uri.contains("login.jsp")
                ||uri.contains("404.jsp")
                ||uri.contains("LoginServlet")
                ||uri.contains("CheckCodeUtile")
                ||uri.endsWith(".js")
                ||uri.endsWith(".css")
                ||uri.contains("layui")
                ||uri.contains("logincss")
                ||uri.contains("imgs")
                ||uri.contains("register.jsp")
                ||uri.contains("register.do")){
            //放行
            chain.doFilter(req, resp);
        }else {
            //获得session中用户对象，如果这个对象是Null则表明用户没有登录需要直接跳转到登录界面
            HttpSession session = request.getSession();
            Object role = session.getAttribute("role");
            if ("role"=="餐厅经理"){
                //跳转到登录界面
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("你没有权限访问");

            }else {
                chain.doFilter(req, resp);
            }
        }

    }

    public void init (FilterConfig config) throws ServletException {

    }

}
